import { ref, computed, onMounted, onUnmounted, readonly } from 'vue'

// Breakpoint definitions
export const breakpoints = {
  mobile: 768,
  tablet: 1024,
  desktop: 1200
} as const

export type BreakpointKey = keyof typeof breakpoints
export type DeviceType = 'mobile' | 'tablet' | 'desktop'

/**
 * Responsive composable for handling screen size detection and layout switching
 */
export function useResponsive() {
  // Reactive screen dimensions
  const screenWidth = ref(0)
  const screenHeight = ref(0)

  // Device type detection
  const isMobile = computed(() => screenWidth.value < breakpoints.mobile)
  const isTablet = computed(() => 
    screenWidth.value >= breakpoints.mobile && screenWidth.value < breakpoints.tablet
  )
  const isDesktop = computed(() => screenWidth.value >= breakpoints.tablet)

  // Current device type
  const deviceType = computed((): DeviceType => {
    if (isMobile.value) return 'mobile'
    if (isTablet.value) return 'tablet'
    return 'desktop'
  })

  // Orientation detection
  const isPortrait = computed(() => screenHeight.value > screenWidth.value)
  const isLandscape = computed(() => screenWidth.value > screenHeight.value)

  // Screen size categories
  const isSmallScreen = computed(() => screenWidth.value < 480)
  const isMediumScreen = computed(() => 
    screenWidth.value >= 480 && screenWidth.value < 768
  )
  const isLargeScreen = computed(() => screenWidth.value >= 768)
  const isExtraLargeScreen = computed(() => screenWidth.value >= 1200)

  // Touch device detection
  const isTouchDevice = computed(() => {
    return 'ontouchstart' in window || navigator.maxTouchPoints > 0
  })

  // Update screen dimensions
  const updateScreenSize = () => {
    screenWidth.value = window.innerWidth
    screenHeight.value = window.innerHeight
  }

  // Debounced resize handler
  let resizeTimer: NodeJS.Timeout | null = null
  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = setTimeout(updateScreenSize, 100)
  }

  // Media query helpers
  const matchMedia = (query: string) => {
    if (typeof window === 'undefined') return false
    return window.matchMedia(query).matches
  }

  const createMediaQuery = (minWidth?: number, maxWidth?: number) => {
    let query = ''
    if (minWidth) query += `(min-width: ${minWidth}px)`
    if (minWidth && maxWidth) query += ' and '
    if (maxWidth) query += `(max-width: ${maxWidth - 1}px)`
    return query
  }

  // Breakpoint utilities
  const isBreakpoint = (breakpoint: BreakpointKey) => {
    switch (breakpoint) {
      case 'mobile':
        return isMobile.value
      case 'tablet':
        return isTablet.value
      case 'desktop':
        return isDesktop.value
      default:
        return false
    }
  }

  const isBreakpointUp = (breakpoint: BreakpointKey) => {
    return screenWidth.value >= breakpoints[breakpoint]
  }

  const isBreakpointDown = (breakpoint: BreakpointKey) => {
    return screenWidth.value < breakpoints[breakpoint]
  }

  const isBreakpointBetween = (min: BreakpointKey, max: BreakpointKey) => {
    return screenWidth.value >= breakpoints[min] && screenWidth.value < breakpoints[max]
  }

  // Layout helpers
  const getColumnsForDevice = () => {
    if (isMobile.value) return 1
    if (isTablet.value) return 2
    return 3
  }

  const getSidebarWidth = () => {
    if (isMobile.value) return 280
    if (isTablet.value) return 280
    return 300
  }

  const shouldShowSidebar = () => {
    return !isMobile.value
  }

  const shouldShowRightPanel = () => {
    return isDesktop.value
  }

  // CSS class helpers
  const getResponsiveClasses = () => {
    return {
      'is-mobile': isMobile.value,
      'is-tablet': isTablet.value,
      'is-desktop': isDesktop.value,
      'is-touch': isTouchDevice.value,
      'is-portrait': isPortrait.value,
      'is-landscape': isLandscape.value,
      'is-small': isSmallScreen.value,
      'is-medium': isMediumScreen.value,
      'is-large': isLargeScreen.value,
      'is-extra-large': isExtraLargeScreen.value
    }
  }

  const getDeviceClass = () => {
    return `device-${deviceType.value}`
  }

  // Orientation change handling
  const orientationChangeCallbacks = ref<(() => void)[]>([])
  
  const handleOrientationChange = () => {
    // Delay to ensure dimensions are updated after orientation change
    setTimeout(() => {
      updateScreenSize()
      orientationChangeCallbacks.value.forEach(callback => callback())
    }, 100)
  }

  const onOrientationChange = (callback: () => void) => {
    orientationChangeCallbacks.value.push(callback)
    return () => {
      const index = orientationChangeCallbacks.value.indexOf(callback)
      if (index > -1) {
        orientationChangeCallbacks.value.splice(index, 1)
      }
    }
  }

  // Lifecycle management
  onMounted(() => {
    updateScreenSize()
    window.addEventListener('resize', handleResize)
    
    // Listen for orientation changes on mobile devices
    if ('orientation' in window) {
      window.addEventListener('orientationchange', handleOrientationChange)
    }
    
    // Also listen for screen orientation API if available
    if (screen.orientation) {
      screen.orientation.addEventListener('change', handleOrientationChange)
    }
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    
    if ('orientation' in window) {
      window.removeEventListener('orientationchange', handleOrientationChange)
    }
    
    if (screen.orientation) {
      screen.orientation.removeEventListener('change', handleOrientationChange)
    }
    
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  })

  return {
    // Screen dimensions
    screenWidth: readonly(screenWidth),
    screenHeight: readonly(screenHeight),
    
    // Device type detection
    isMobile: readonly(isMobile),
    isTablet: readonly(isTablet),
    isDesktop: readonly(isDesktop),
    deviceType: readonly(deviceType),
    
    // Orientation
    isPortrait: readonly(isPortrait),
    isLandscape: readonly(isLandscape),
    
    // Screen size categories
    isSmallScreen: readonly(isSmallScreen),
    isMediumScreen: readonly(isMediumScreen),
    isLargeScreen: readonly(isLargeScreen),
    isExtraLargeScreen: readonly(isExtraLargeScreen),
    
    // Touch device
    isTouchDevice: readonly(isTouchDevice),
    
    // Breakpoint utilities
    breakpoints,
    isBreakpoint,
    isBreakpointUp,
    isBreakpointDown,
    isBreakpointBetween,
    
    // Layout helpers
    getColumnsForDevice,
    getSidebarWidth,
    shouldShowSidebar,
    shouldShowRightPanel,
    
    // CSS helpers
    getResponsiveClasses,
    getDeviceClass,
    
    // Media query helpers
    matchMedia,
    createMediaQuery,
    
    // Orientation change
    onOrientationChange,
    
    // Manual update
    updateScreenSize
  }
}

